import mongoose, { Document, Schema } from 'mongoose';

export interface ICartItem extends Document {
  user: mongoose.Types.ObjectId;
  product: mongoose.Types.ObjectId;
  quantity: number;
  attributes: Record<string, any>;
  selected: boolean;
  createdAt: Date;
  updatedAt: Date;
}

const CartItemSchema: Schema = new Schema(
  {
    user: {
      type: Schema.Types.ObjectId,
      ref: 'User',
      required: true,
    },
    product: {
      type: Schema.Types.ObjectId,
      ref: 'Product',
      required: true,
    },
    quantity: {
      type: Number,
      required: true,
      min: 1,
      default: 1,
    },
    attributes: {
      type: Map,
      of: Schema.Types.Mixed,
      default: {},
    },
    selected: {
      type: Boolean,
      default: true,
    },
  },
  {
    timestamps: true,
  }
);

// 创建复合索引，防止用户对同一商品多次加入购物车
CartItemSchema.index({ user: 1, product: 1 }, { unique: true });

export default mongoose.model<ICartItem>('CartItem', CartItemSchema); 